<script setup>
import { onMounted, nextTick, ref, reactive, watch, computed, h } from 'vue'
import 'leaflet/dist/leaflet.css'
import * as L from 'leaflet'
import "leaflet-polylinedecorator"
import "leaflet.marker.slideto"
import Html2canvas from "html2canvas";
import img1 from "../assets/dog.png"
import 'leaflet.pm'
import 'leaflet.pm/dist/leaflet.pm.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import kscreenshot from 'kscreenshot'
// import world from "../assets/json/世界国界geojson.json"
// import world from "../assets/json/河北省 (2).json"
import world from "../assets/json/storm_20220819.json"

const uuu = "http://115.29.149.99:8054"
// console.log(world);
// import * as turf from '@turf/turf'
// import 'geoman-io/leaflet-geoman-free/dist/leaflet-geoman.min';   
// import 'geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css';
const zqq = '/zqq'
const url = "/api"
const mapWidth = ref(200)
let blocks = []
let allLayer = []

let currentTime = ref(""),
  mapRef = ref(),
  canvasNum = ref([]),
  canvasSty = ref({}),
  canvasNum2 = ref([]),
  canvasSty2 = ref({})
let mapObj = {
  zoom: 4
}
let layerControl = null
let isclick = false
let marker = null

const testUrl = '/test'

// onMounted(()=>{
//   setInterval(()=>{
//     mapWidth.value+=100
//     mapObj.map.invalidateSize(true)
//   },1000)
// })

onMounted(() => {
  // for (let i = 0; i < 30; i++) {
  //   axios({
  //     method: "get",
  //     url: testUrl + '/limit'
  //   }).then(res => {
  //     console.log(res);
  //   })
  // }

  // axios({
  //   method: "get",
  //   url: uuu+"/outlook/W2_COLD"
  // }).then(res => {
  //   console.log(res);
  // })
  // s={
  //   a:[32,32],
  //   b:3,
  //   c:[
  //     {
  //       a:3
  //     }
  //   ]
  // }

  // nextTick(()=>{
  //   console.log(s);
  // })

  // console.log(s);

  //||这叫有一个存在就行（undefinded和null被认为是不存在），第一个存在就第一个
  //&&同时存在的话选大的
  //&&两边是null和undefined时候，返回第一个，我觉得可能是先拿第一个的值，检查第二的时候发现也不行，就直接返回第一个的值
  // let a
  // let b=a&&null
  // console.log(b);
  // // ===不进行数值转换
  // console.log(Object.is(a,null),undefined==null,0===null);

  // // assign浅拷贝，输入的参数在外部的改变都会引起新值得改变。。同名替换
  // let obj={a:2}
  // let nobj=Object.assign(obj,{b:2})
  // obj.a=4
  // console.log(nobj)
  // return 
  // class Point {
  //   constructor(x, y) {
  //     this.x = x;
  //     this.y = y;
  //   }

  //   toString() {
  //     return '(' + this.x + ', ' + this.y + ')';
  //   }
  // }

  // console.log(Object.assign({ b: 5 }, { s: 8 }, { a: 5 },{..."sdsd"}));

  //await对定时器不起作用但是对Promise起作用

  // const aaa = async () => {
  //   let pp = new Promise((resolve, reject) => {
  //     setTimeout(() => {
  //       resolve()
  //     }, 1000)
  //   })
  //   pp.then(res => {
  //     console.log(111);
  //   })
  // }

  // 000同步肯定先输出，0.4进宏，next进微，1000ms的定时器进第二个宏
  //await需要等，不管多块主线程都会直接读取异步的任务队列，next肯定先走，再resolve执行，
  //resolve的执行是生成了一个微任务放到了异步队列，这是一定的
  //await存在resolve的执行可不是瞬发激活那个函数的，也是生成了一个微任务放队列
  //主线程遇到await就相当于遇到了阻塞，就会马上拉去异步队列开始从头执行
  // const readSome = async () => {
  //   console.log("000");
  //   setTimeout(() => {
  //     console.log("0.4");
  //   }, 1000)
  //   nextTick(() => {
  //     console.log("next");
  //   })
  //   let pp = new Promise((resolve, reject) => {
  //     setTimeout(() => {
  //       nextTick(() => {
  //         resolve()
  //       })
  //     }, 1000)
  //   })
  //   nextTick(() => {
  //     console.log("mid");
  //   })
  //   await pp.then(res => {
  //     console.log(111);
  //   })
  //   console.log(222);
  // }
  // readSome()

  // var myObject = {
  //   foo: 1,
  //   bar: 2,
  //   baz() {
  //     console.log(this.bar, super.bar);
  //     return this.foo + this.bar;
  //   },
  // }


  // var p = new Point(1, 2);
  // console.log(p);
  // function outer() {
  //   var a = '123'
  //   return a
  //   return function add() {　　　　//在这里因为作用域的关系，add是能访问到outer的所有变量的，但是outer是访问不到add的变量；　　　　//所以思路一转，把add的值作为结果return出来变通实现outer外部函数访问到了内部函数变量    // add就是一个闭包函数，因为他能够访问到outer函数的作用域，add中没有找到变量a，则会继续往上层作用域找     
  //     // console.log(a);
  //     return a
  //   }
  // }
  // var inner = outer()
  // console.log(inner);
  // console.log(inner());
  // const a=(ms)=>{
  //   return new Promise((success,fail)=>{
  //     setTimeout(()=>{
  //       success("ssss")
  //     },ms)
  //   })
  // }

  // a(2000).then(res=>{
  //   console.log(res,555);
  // })
  // console.log(a);

  // setTimeout(() => {
  //   console.log(2);
  // }, 0)
  // new Promise((res, a) => {
  //   console.log(1);
  //   // res()
  //   a()
  // }).then(() => {
  //   console.log(4);
  // }).catch(() => {
  //   console.log(5);
  // })
  // console.log(3);

  // return

  // setInterval(() => {
  //   currentTime.value = new Date()
  // }, 1000);
  // let map = L.map('map', {
  //   center: [51.505, -0.09],
  //   zoom: 5
  // });
   let map = L.map('map', {
    attributionControl: false, 
    crs: L.CRS.EPSG3857,
    zoomControl: false,
    maxBounds: null
  }).setView([0, 116.404], mapObj.zoom)

  mapObj.map = map
  // L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', { foo: 'bar', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(mapObj.map);
  L.tileLayer(
    "http://39.103.180.154:1001/mapTile/arcgisonline/{z}/{y}/{x}.png"
  ).addTo(mapObj.map);
  //   
  // console.log(document.body.clientWidth);
  

  // setInterval(()=>{
  //   // 打印地图边界
  //   console.log(mapObj.map.getPixelBounds());
    
  // },1000)
  // mapObj.map.pm.setPathOptions({
  //   fillOpacity: 0.5,
  //   color: "orange",
  //   fillColor: "green",
  // })
  mapObj.map.pm.setLang('zh');
  mapObj.map.pm.addControls({
  position: 'topleft',
  drawCircle: false,
});
  // mapObj.map.pm.addControls({
  //   position: "topleft",
  //   drawPolygon: false, // 绘制多边形
  //   drawMarker: false, //绘制标记点
  //   drawCircleMarker: false, //绘制圆形标记
  //   drawPolyline: false, //绘制线条
  //   drawRectangle: true,	//绘制矩形
  //   drawCircle: false, //绘制圆圈
  //   editMode: true, //编辑多边形
  //   dragMode: true, //拖动多边形
  //   cutPolygon: false, // 添加一个按钮以删除多边形里面的部分内容
  //   removalMode: true  // 清除多边形
  // }).addTo(mapObj.map);
  return
  mapObj.map.on('pm:create', (e) => {
    // console.log(mapObj.map);

    // console.log(currentLayer);
    // 转为屏幕坐标
    let bounds = e.layer.getBounds()

    let northWest = bounds.getNorthWest()
    let southEast = bounds.getSouthEast()

    let northWestPoint = mapObj.map.latLngToLayerPoint(northWest)
    let southEastPoint = mapObj.map.latLngToLayerPoint(southEast)

    let mapBounds=mapObj.map.getBounds()

    let p1=mapBounds.getNorthWest()
    let p2=mapBounds.getSouthEast()

    let rate1=document.body.clientWidth/(p2.lng-p1.lng)
    let rate2=document.body.clientHeight/(p1.lat-p2.lat)
    
    

    let width = southEastPoint.x - northWestPoint.x
    let height = southEastPoint.y - northWestPoint.y
    // let width = (southEast.lng-northWest.lng)*rate1
    // let height = (northWest.lat-southEast.lat)*rate2
    styMap.width = width + 'px'
    styMap.height = height + 'px'
    styMap.left = (northWest.lng-p1.lng)*rate1+'px' 
    styMap.top = (p1.lat-northWest.lat)*1.02*rate2+'px'

    // console.log(p1.lat-northWest.lat);
    
    // styMap.left = northWestPoint.x + 'px'
    // styMap.top = northWestPoint.y + 'px'

    // console.log(styMap.left,styMap.top,width,height); 
    // 值拷贝bounds


    mapObj.map.setMaxBounds(bounds)
    // mapObj.map.fitBounds(bounds)
    // console.log(mapObj.map.maxBounds);
    // mapObj.map.setView([center.lat, center.lng], mapObj.map.getZoom())


    setTimeout(() => {
      mapObj.map.invalidateSize()
    }, 500)

    currentLayer = e.layer
    // console.log(currentLayer._map);

    // 提示下载
    ElMessageBox.confirm(
      '是否保存为图片?',
      '提示',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
    )
      .then(() => {
        mapObj.map.removeLayer(currentLayer)
        // console.log(currentLayer);
        // console.log('1111');
        
        
        styMap.width = '100%'
        styMap.height = '100%'
        styMap.left = '0'
        styMap.top = '0'
        ElMessage({
          type: 'success',
          message: '保存成功',
        })
        shotMap()
        setTimeout(() => {
          mapObj.map.setMaxBounds(null)
          mapObj.map.invalidateSize()

        }, 500)
      })
      .catch(() => {
        mapObj.map.removeLayer(currentLayer)
        ElMessage({
          type: 'info',
          message: '保存取消',
        })
      })
  });

  // L.geoJSON(world.storm).addTo(mapObj.map)

  // 判断点是否在多边形内
  // let isInside = turf.booleanPointInPolygon([116.404, 39.915], world)
  // world.geometries.forEach((item, idx) => {
  //   item.coordinates.forEach((item2, idx2) => {
  //     item2.forEach((item3, idx3) => {
  //         item3.forEach((item4, idx4) => {
  //           L.circle([item4[1], item4[0]], {
  //             color: 'red',
  //             fillColor: '#f03',
  //             fillOpacity: 0.5,
  //             radius: 1000
  //           }).addTo(mapObj.map)
  //         })

  //     })
  //   })
  // })



  // 使用form-data进行请求
  // let formData = new FormData();
  // formData.append('lon1', '116.404');
  // formData.append('lat1', '39.915');
  // formData.append('lon2', '120.405');
  // formData.append('lat2', '35.915');
  // axios({
  //   method: 'post',
  //   url: zqq + '/getgeodesic',
  //   // data: { lon1: "116.404", lat1: "39.915", lon2: "120.405", lat2: "35.915" },
  //   data: formData,
  // }).then(res => {
  //   console.log(res);
  //   // 画线
  //   let latlngs = res.data
  //   console.log(latlngs);
  //   latlngs.forEach((item, index) => {
  //     if (index === latlngs.length - 1) {
  //       return
  //     }
  //     L.polyline([
  //       [item.latitude, item.longitude],
  //       [latlngs[index + 1].latitude, latlngs[index + 1].longitude],
  //     ], {
  //       color: 'red',
  //     }).addTo(mapObj.map)
  //   })
  // })


  // 鼠标选择起始点和终点，并在鼠标上方提示当前要选择的点，将起始点和终点的经纬度传给后台zqq + '/getgeodesic'




  return
  canvasSty.value = {
    right: 1707 - mapRef.value.offsetLeft + "px"
  }

  // showLatLng(mapObj.zoom, mapObj.map.getBounds())
  // watchZoom()
  // watchMove()

  let layer = initPoint()
  initControl(layer)

  // map.createPane('labels');
  // testLayer()
  let arrPosition = [[58.44773, -28.65234], [52.9354, -23.33496], [53.01478, -14.32617], [58.1707, -10.37109], [59.68993, -0.65918]]
  var polyline = L.polyline([[58.44773, -28.65234], [52.9354, -23.33496], [53.01478, -14.32617], [58.1707, -10.37109], [59.68993, -0.65918]], { weight: 10 })
  var polyline1 = L.polyline([[58.44773, -28.65234], [52.9354, -23.33496], [53.01478, -14.32617], [58.1707, -10.37109], [59.68993, -0.65918], [60.68993, -0.65918]], { color: 'green', weight: 5 })
  polyline1.addTo(mapObj.map)
  polyline.addTo(mapObj.map)
  let markerStart = L.circleMarker([58.44773, -28.65234], { radius: 5, color: "red", opacity: 1 }).addTo(mapObj.map)
  // arrPosition.forEach(item => {
  //   markerStart.slideTo(item, {
  //     duration: 2000,
  //     keepAtCenter: true
  //   })
  // })
  let num = 2
  markerStart.slideTo(arrPosition[1], {
    duration: 1000,
    keepAtCenter: false
  })
  setInterval(() => {
    markerStart.slideTo(arrPosition[num], {
      duration: 1000,
      keepAtCenter: false
    })
    num++
  }, 1000)


  var decorator = L.polylineDecorator(polyline, {
    patterns: [
      {
        offset: 10,
        endOffset: 0,  // 箭头起始位置距离线条两端的距离
        repeat: 60,  // 箭头重复的间隔
        symbol: L.Symbol.arrowHead({
          pixelSize: 15,  // 箭头大小
          headAngle: 95,
          polygon: false,
          pathOptions: { stroke: true, weight: 4, color: 'red' }
        })
      }
    ]
  }).addTo(mapObj.map);
  // mapObj.map.removeLayer(decorator)
  // polyline.getPane("labels").style.zIndex=400
})

const domm = {
  render() {
    return h('div', {
      id: 'hello'
    }, "2222")
  }
}

const initPoint = () => {
  // let dom = h('div', { class: 'bar', innerHTML: 'hello' })

  let layer = L.circleMarker([30.71689, 122.468765], {
    radius: 5,
    color: "red",
  }).addTo(mapObj.map).bindPopup("wedasd")
  let btn = document.getElementById("save-btn")

  // const vnode = <div>hello</div>
  let myIcon = L.divIcon({
    html: domm,
    iconSize: "40px",
    className: 'my-div-icon',
  })
  // L.marker([30.71989, 122.479765], {
  //   icon: myIcon,
  //   draggable: true,
  // }).addTo(mapObj.map)
  let lg = L.layerGroup([layer])
  // lg.bindPopup("popupContent").openPopup();
  return lg
},
  initControl = (pointLayer) => {
    let overlayLayers = {
      测站: pointLayer,
    }
    // pointLayer.addTo(mapObj.map)
    layerControl = L.control.layers(null, overlayLayers).addTo(mapObj.map);
  }

  ,
  testLayer = () => {
    // let layer = L.circleMarker([30.71689, 122.468765], {
    //   radius: 5,
    //   color: "red",
    // })

    // marker是特定图标的标记

    let layer = L.marker([30.71689, 122.468765], {
      title: "sss",
      opacity: 0.5,
      draggable: true,
      autoPan: true
    })
    layer.on('dragstart', (e) => {
      console.log(e);
    });
    mapObj.map.addLayer(layer)
    // layer.bindTooltip("my tooltip text").openTooltip();
    layer.bindPopup("popupContent").openPopup();
  }

// addLayer = () => {
//   let layer=bbb().addTo(mapObj.map)
//   console.log(layer);
// },
// deleteLayer = () => {
//   aaa(lg)
//   // lg.clearLayers()
//   // console.log(lg.getLayers());
// },
// aaa = (lgCopy) => {
//   console.log(lgCopy.getLayers());
//   lgCopy.clearLayers()
// },
// bbb = () => {
//   let layer = L.circleMarker([30.71689, 122.468765], {
//     radius: 5,
//     color: "red",
//   })
//   // let lg=L.layerGroup([layer])
//   // lg.addLayer(layer)
//   return L.layerGroup([layer])
// }
const watchZoom = () => {
  mapObj.map.on('zoomend', (e) => {
    mapObj.zoom = e.target.getZoom()
    showLatLng(e, mapObj.map.getBounds())
  });
},
  watchMove = () => {
    mapObj.map.on('move', (e) => {
      showLatLng(mapObj.zoom, mapObj.map.getBounds())
    });
  },
  showLatLng = (e, bounds) => {
    let currentZoom = e > 0 ? e : e.target.getZoom()
    let step = 0.1
    let startLat = Math.ceil(bounds._southWest.lat * 100) / 100
    let startLng = Math.ceil(bounds._southWest.lng * 100) / 100
    if (currentZoom < 10 && currentZoom > 7) {
      step = 1
      startLat = Math.ceil(startLat)
      startLng = Math.ceil(startLng)
    } else if (currentZoom < 7) {
      step = 2
      startLat = Math.ceil(startLat)
    }
    canvasNum.value = []
    canvasNum2.value = []
    for (let i = startLat; i < bounds._northEast.lat; i = i + step) {
      canvasNum.value.push(i.toFixed(2))
    }
    for (let i = startLng; i < bounds._northEast.lng; i = i + step) {
      canvasNum2.value.push(i.toFixed(2))
    }
    nextTick(() => {
      for (let i = 0; i < canvasNum.value.length; i++) {
        let cans = document.getElementById("canvas" + i)
        let top = 130 + 600 * (bounds._northEast.lat - canvasNum.value[i]) / (bounds._northEast.lat - bounds._southWest.lat) - 16
        cans.style.top = top + "px"
      }
      for (let i = 0; i < canvasNum2.value.length; i++) {
        let cans = document.getElementById("canvas2" + i)
        let left = 252 + 1200 * (bounds._northEast.lng - canvasNum2.value[i]) / (bounds._northEast.lng - bounds._southWest.lng) - 30
        console.log(mapRef.value.offsetLeft);
        cans.style.left = left + "px"
      }
    })
  },
  draw = (i) => {
    let canvas = document.getElementById("tutorial" + i),
      ctx = canvas.getContext("2d"),
      width = canvas.width,
      height = canvas.height;
    ctx.beginPath();
    ctx.strokeStyle = "blue";
    ctx.lineWidth = 0.6;
    ctx.moveTo(width / 2, height / 2,);
    ctx.lineTo(0, 0);
    ctx.stroke();
  }

const Render = (src, width, height, cb) => {
  const img = new Image();
  img.src = src;
  img.width = width;
  img.height = height;
  img.crossOrigin = ""; // 图像跨域时配置
  cb && cb(img);
},
  Download = (url, name) => {
    const target = document.createElement("a");
    target.href = url;
    target.download = name;
    const event = document.createEvent("MouseEvents");
    event.initEvent("click", true, true);
    target.dispatchEvent(event);
  }
const shotMap = () => {
  // mapObj.map.removeControl(layerControl)
  const screenshot = document.getElementById("map");
  const opts = {
    logging: false,
    scale: 2,
    useCORS: true
  };
  Html2canvas(screenshot, opts).then(res => {
    const { height, width } = res;
    const base64 = res.toDataURL("image/png", 1);
    Render(base64, width, height, img => {
      Download(base64, "screenshot.png");
    });
  }, err => alert("截图失败，请重新尝试"));
}

const values = ref([
  {
    src: "https://iconfont.alicdn.com/p/illus_3d/preview_image/6ysIeM30bNwA/4b47568f-0617-40a5-8d21-a081b239118e.png"
  },
  {
    src: "https://iconfont.alicdn.com/p/illus_3d/preview_image/6ysIeM30bNwA/b5a887c6-5e78-4d01-91b4-79575121491f.png"
  },
  {
    src: "https://iconfont.alicdn.com/p/illus_3d/preview_image/6ysIeM30bNwA/ec7e1b53-2355-4d7c-9477-157115e10d31.png"
  },
  {
    src: "https://iconfont.alicdn.com/p/illus_3d/preview_image/6ysIeM30bNwA/d5f4de92-173d-4b4e-b9c0-ea3b7ab77996.png"
  },
  // {
  //   src: "https://iconfont.alicdn.com/p/illus_3d/preview_image/6ysIeM30bNwA/ea9a63fd-32d1-4d75-b53d-96ae0beb2a4e.png"
  // },
  // {
  //   src: "https://iconfont.alicdn.com/p/illus_3d/preview_image/6ysIeM30bNwA/fa4ef0cd-b14a-4735-aadd-ec23706a869b.png"
  // },
])

const sty = reactive({
  boxShadow: "0px 0px 15px #888888",
  // width: "80px"

})
const sty1 = reactive({
  // width: "0px",
  // opacity: 0,
  // transform: "translateX(-80px)"
})
const sty2 = reactive({
  boxShadow: "0px 0px 15px #888888",
  // border:"2px solid #888888",
  borderRadius: "50px"
})
const sty3 = reactive({
  boxShadow: "0px 0px 15px transparent",
  // border:"2px solid transparent",
  borderRadius: "50px"
})
const hoverId = ref(null),
  isFold = ref(false)

let currentLayer = {}

const itemClick = (idx) => {
  if (idx != 0) return
  isFold.value = !isFold.value

  // sty1.display = "none"
},
  itemEnter = (idx) => {
    hoverId.value = idx
  },
  itemLeave = () => {
    hoverId.value = null
  },
  dealSty = (idx) => {
    if (isFold.value) {
      if (idx != 0) {
        // return sty1
        return sty
      } else {
        return reactive({
          transform: "rotateZ(360deg)",
        })
      }
    }
    else {
      if (idx != hoverId.value) {
        return sty
      } else {
        return reactive({
          boxShadow: "",
          // transform: "rotateZ(360deg)",
          // width: "200px",
        })
      }
    }
  },
  imgClick = (idx) => {
    if (idx == 1) {
      mapObj.map.removeLayer(currentLayer)
      mapObj.map.pm.enableDraw('Rectangle', {
        snappable: true,
        snapDistance: 20,
        allowSelfIntersection: false
      });
    } else if (idx == 2) {
      if (isclick) {
        mapObj.map.off('mousemove')
        mapObj.map.off('click')
        isclick = false
        mapObj.map.removeLayer(marker)
        return
      }
      isclick = true
      let latlngs = []
      // 圆形白色背景蓝色边框的点
      marker = L.circleMarker([0, 0], {
        radius: 7,
        color: '#0000ff',
        fillColor: '#ffffff',
        fillOpacity: 1,
      }).addTo(mapObj.map)
      // marker开启tooltip
      marker.bindTooltip('请选择起点', {
        permanent: true,
        direction: 'top',
        className: 'marker-tooltip',
      }).openTooltip()
      mapObj.map.on('mousemove', (e) => {
        marker.setLatLng(e.latlng)
      })
      mapObj.map.on('click', (e) => {
        latlngs.push(e.latlng)
        if (latlngs.length === 3) {
          // 清空所有实体
          // mapObj.map.removeLayer(marker)
        }
        if (latlngs.length === 2) {
          // 传给后台
          let formData = new FormData();

          formData.append('start_lon1', latlngs[0].lng);
          formData.append('start_lat1', latlngs[0].lat);
          formData.append('stop_lon2', latlngs[1].lng);
          formData.append('stop_lat2', latlngs[1].lat);

          // 画出起始点和终点,icon为蓝色圆点
          let marker1 = L.circleMarker(latlngs[0], {
            radius: 4,
            color: '#0000ff',
            fillColor: '#0000ff',
            fillOpacity: 1,
          }).addTo(mapObj.map)
          allLayer.push(marker1)

          // 以起点为中心边长为1度的正方形
          // 画出正方形
          // currentLayer = L.rectangle([[latlngs[0].lat,latlngs[0].lng],[latlngs[0].lat+1,latlngs[0].lng+1]], {
          //   color: "#0000ff",
          //   weight: 1,
          //   fill: false,
          //   fillOpacity: 0.2,
          // }).addTo(mapObj.map)

          let marker2 = L.circleMarker(latlngs[1], {
            radius: 4,
            color: '#0000ff',
            fillColor: '#0000ff',
            fillOpacity: 1,
          }).addTo(mapObj.map)
          allLayer.push(marker2)

          let start = [Math.floor(latlngs[0].lat * 10000) / 10000, Math.floor(latlngs[0].lng * 10000) / 10000]
          let goal = [Math.floor(latlngs[1].lat * 10000) / 10000, Math.floor(latlngs[1].lng * 10000) / 10000]
          if (start[0] > 15 && start[0] < 41 && start[1] > 105 && start[1] < 125) {
            // 互换start和goal
            let temp = start
            start = goal
            goal = temp
          }

          axios({
            method: "post",
            data: {
              start: start,
              goal: goal,
              // 四位小数
              barrier: [[400, 40], [430, 540]]
            },
            url: url + "/star/base"
          })
            .then(res => {
              console.log(res);
              if (res.data.code == -1) {
                latlngs = []
                return
              }
              // 画线
              // let lines = res.data.data.lines
              let lines = res.data.data.all
              let markers = res.data.data.openList
              blocks = res.data.data.blocks
              // 画矩形

              // markers.forEach(item => {
              //   L.circleMarker([item[0], item[1]], {
              //     radius: 3,
              //     color: 'black',
              //     fillColor: 'black',
              //     fillOpacity: 1,
              //   }).addTo(mapObj.map)
              // })
              let lines1 = L.polyline([
                // [Math.floor(latlngs[1].lat * 10000) / 10000, Math.floor(latlngs[1].lng * 10000) / 10000],
                goal,
                [lines[0][0], lines[0][1]],
              ], {
                color: 'red',
                weight: 2,
              }).addTo(mapObj.map)
              allLayer.push(lines1)
              lines.forEach((item, index) => {
                if (index === lines.length - 1) {
                  let marker3 = L.circleMarker([item[0], item[1]], {
                    radius: 3,
                    color: 'green',
                    fillColor: 'green',
                    fillOpacity: 1,
                  }).addTo(mapObj.map)
                  allLayer.push(marker3)
                  return
                }
                let lines2 = L.polyline([
                  [item[0], item[1]],
                  [lines[index + 1][0], lines[index + 1][1]],
                ], {
                  color: 'red',
                  weight: 1.5,
                }).addTo(mapObj.map)
                allLayer.push(lines2)
                // 画zhuandian
                // L.circleMarker([item[0], item[1]], {
                //   radius: 3,
                //   color: 'green',
                //   fillColor: 'green',
                //   fillOpacity: 1,
                // }).addTo(mapObj.map)
              })
              let lines3 = L.polyline([
                [lines[lines.length - 1][0], lines[lines.length - 1][1]],
                // [Math.floor(latlngs[0].lat * 10000) / 10000, Math.floor(latlngs[0].lng * 10000) / 10000],
                start,
              ], {
                color: 'red',
                weight: 2,
              }).addTo(mapObj.map)
              allLayer.push(lines3)

              // lines.forEach((item, idx) => {
              //   if(idx === lines.length - 1) return
              //   L.polyline([
              //     [item.X, item.Y],
              //     [lines[idx + 1].X, lines[idx + 1].Y],
              //   ], {
              //     color: 'red',
              //   }).addTo(mapObj.map)
              // })
              latlngs = []


              // blocks.forEach(item => {
              //   // 间隔一秒画一个矩形
              //   // setTimeout(() => {
              //     L.rectangle([[item[0], item[1]], [item[2], item[3]]], {
              //       color: 'yellow',
              //       weight: 1,
              //       opacity: 0.5,
              //     }).addTo(mapObj.map)
              //   // }, 1000)
              // })

            })
        } else {
          // 设置marker的tooltip
          marker.bindTooltip('请选择终点', {
            permanent: true,
            direction: 'top',
            className: 'marker-tooltip',
          }).openTooltip()
        }
      })
    } else {
      // 清空所有实体
      allLayer.map((item) => {
        mapObj.map.removeLayer(item)
      })
      // axios({
      //   method: "post",
      //   data: {
      //     // 
      //     start: [],
      //     goal: [],
      //     barrier: [[400, 40], [430, 540]]
      //   },
      //   url: url + "/star/base"
      // })
      //   .then(res => {
      //     console.log(res);
      //     // 画线
      //     let lines = res.data.data.lines
      //     lines.forEach((item, index) => {
      //       if (index === lines.length - 1) {
      //         return
      //       }
      //       L.polyline([
      //         [item[0], item[1]],
      //         [lines[index + 1][0], lines[index + 1][1]],
      //       ], {
      //         color: 'red',
      //         weight: 2,
      //       }).addTo(mapObj.map)
      //     })
      //   })
    }
  }

const ocrPic = () => {
  new kscreenshot({
    key: 65,
    needDownload: true,
    endCB(e) { //截图成功回调
      console.log(e)
    },
    cancelCB(e) { //截图失败回调
      console.log(e)
    }
  }).startScreenShot()
}

const styMap = reactive({
  width: '100%',
  height: '100%',
  position: 'absolute',
  top: '0',
  left: '0',
})
</script>

<template>
  <div id="contain">
    <!-- <p>{{currentTime}}</p> -->
    <!-- <div style="height: 200px;width: 100px;position: absolute;"> -->

    <div ref="mapRef" id="map" :style="styMap"></div>

    <div id="contain1" style="margin-left: 15px;">
      <div class="item" v-for="(item, idx) in values" @click="itemClick(idx)" @mouseenter="itemEnter(idx)"
        @mouseleave="itemLeave" :style="hoverId == idx && idx != 0 ? sty2 : sty3">
        <Transition name="img">
          <img :src=item.src :style="dealSty(idx)" v-if="!isFold || idx == 0" @click="imgClick(idx)">
        </Transition>
      </div>
    </div>

    <!-- <el-button type="warning" @click="ocrPic" icon="el-icon-camera">开始截图</el-button> -->


    <!-- </div> -->
    <!-- <div v-for="(item,index) in canvasNum" class="tips" :id="'canvas'+index" style="top:0px" :style="canvasSty">
                  <div class="tipsTitle">{{item}}N</div>
                  <canvas class="canvasC1"></canvas>
                </div>
                <div v-for="(item,index) in canvasNum2" class="tips2" :id="'canvas2'+index" style="left:40px;top: 735px;"
                  :style="canvasSty2">
                  <canvas class="canvasC2"></canvas>
                  <div class="tipsTitle">{{item}}E</div>
                </div> -->

    <!-- <div style="display: flex;width: 500px;justify-content: space-between;background-color: blue;">
                  <el-button type="primary" size="default" @click="addLayer">添加</el-button>
                  <el-button type="warning" size="default" @click="deleteLayer">删除</el-button>
                  <button id="save-btn" @click="shotMap" style="width: 60px;background-color: aqua;">保存</button>
                </div> -->
  </div>
</template>

<style lang="less">
#contain {
  // display: flex;
  // flex-direction: column;
  // height: 100vh;

  .my-div-icon {
    width: 30px;
    height: 30px;
    background-color: red;
  }

  .bar {
    height: 200px;
    width: 200px;
    background-color: aqua;
  }

  .leaflet-top {
    display: none;
  }

  #contain1 {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 9999;

    .item {
      margin: 5px;
      caret-color: transparent;
      cursor: pointer;
      display: flex;

      .img-enter-from,
      .img-leave-to {
        opacity: 0;
        transform: translateX(-100px);
      }

      .v-enter-active {
        transition: opacity 0.3s ease;
      }

      .v-enter-from,
      .v-leave-to {
        opacity: 0;
      }

      img {
        // height: 80px;
        // width: 80px;
        height: 50px;
        width: 50px;
        border-radius: 50px;
        transition: all 0.3s;
      }
    }
  }


  #map {}

  .canvasC1 {
    background-color: black;
    margin-top: 20px;
    height: 2px;
    width: 15px;
  }

  .canvasC2 {
    background-color: black;
    height: 15px;
    width: 2px;
    margin-left: 30px;
  }

  .tips {
    display: flex;
    position: absolute;

    .tipsTitle {
      margin-top: 7px;
      margin-right: 10px;
    }
  }

  .tips2 {
    // display: flex;
    position: absolute;

    // flex-direction: column;
    .tipsTitle {}
  }

}
</style>